import os
import zipfile
from time import sleep

import paramiko

from models.RedisOperation import RedisClient


class TranReport(object):
    r = RedisClient()

    def send_report(self, order_number):
        # 远程服务器的地址和端口
        hostname = '118.195.199.198'
        port = 22

        # 远程服务器的用户名和密码
        username = 'ubuntu'
        password = 'Aa19950218!'

        # 远程文件路径和本地文件路径
        local_path = '/mnt/nas/report/samereport_' + order_number + '.zip'
        remote_path = '/mnt/report/samereport_' + order_number + '.zip'

        # 创建 SSH 客户端
        ssh_client = paramiko.SSHClient()

        # 自动添加远程服务器的主机密钥
        ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        # 连接到远程服务器
        ssh_client.connect(hostname, port=port, username=username, password=password)

        # 创建 SCP 客户端
        scp_client = ssh_client.open_sftp()

        # 从远程服务器下载文件到本地系统
        scp_client.get(remote_path, local_path)

        # 关闭 SCP 客户端和 SSH 客户端
        scp_client.close()
        ssh_client.close()
        target_dir = '/mnt/nas/report/'
        with zipfile.ZipFile('/mnt/nas/report/samereport_' + order_number + '.zip', 'r') as zip_ref:
            # 解压缩所有文件到指定目录
            zip_ref.extractall(target_dir)


if __name__ == '__main__':
    bot = TranReport()
    while True:
        order_number = bot.r.db.rpop('tran_report')
        if order_number:
            print(order_number)
            bot.send_report(order_number)
        else:
            sleep(3)
